package com.abe.bathsystem.android.v3;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Looper;
import android.view.View;

import com.abe.bathsystem.api.AppMainService;
import com.abe.bathsystem.base.ManagerLocalData;
import com.abe.bathsystem.base.ManagerTimer;
import com.abe.bathsystem.entity.ReqBaseEntity;
import com.abe.bathsystem.entity.ReqConstant;
import com.abe.bathsystem.entity.http.HttpBathPosStateEntity;
import com.abe.bathsystem.entity.http.HttpGPushEntity;
import com.abe.bathsystem.entity.http.HttpRoomEntity;
import com.abe.bathsystem.entity.http.HttpSensorEntity;
import com.abe.bathsystem.entity.http.HttpUserDetailEntity;
import com.abe.bathsystem.entity.http.HttpUserEntity;
import com.abe.bathsystem.entity.serial.DeviceTemperatureEntity;
import com.abe.bathsystem.entity.serial.DeviceWaterUsageEntity;
import com.abe.bathsystem.entity.serial.SerialCommandEntity;
import com.abe.bathsystem.utils.NormalUtils;
import com.abe.bathsystem.utils.SerialPortUtils;
import com.abe.bathsystem.widget.dialog.BathControlDialog;
import com.abe.bathsystem.widget.dialog.ChooseBathPosDialog;
import com.abe.bathsystem.widget.dialog.DialogContract;
import com.abe.bathsystem.widget.dialog.LoginMainDialog;
import com.abe.bathsystem.widget.dialog.LoginQuickDialog;
import com.abe.bathsystem.widget.dialog.MessageDialog;
import com.abe.libcore.utils.normal.CommonUtils;

import net.yet.campusdev.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//os参数填写dev
//测试登录用户：15098760059,123456
public class MainBathShowActivity extends MainBathSerialPortActivity implements BathControlDialog.OnBathControlListener, DialogContract.OnLoginListener {

    //房间洗浴位数据
    protected List<HttpBathPosStateEntity> posStateEntities;
    //当前登录操作洗浴位
    protected HttpBathPosStateEntity posStateEntity;
    //当前登录人
    protected HttpUserEntity userEntity;

    //自动上锁计时
    private int timeOutControlNum = 0;
    //自动更新传感器值计时
    private int timeOutTemperature = 0;
    // SoundPool对象
    private SoundPool mSound;
    private int[] mSoundID;

    @Override
    public void initContent() {
        super.initContent();
        mSoundID = new int[16];
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            mSound = new SoundPool.Builder()
                    .setMaxStreams(1)
                    .build();
        } else {
            mSound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        }
        initMusic();
    }

    /**
     * 初始化音频文件
     */
    private void initMusic() {
        //分别加入到SoundPool中
        mSoundID[0] = mSound.load(this, R.raw.startbath01, 1);// 1
        mSoundID[1] = mSound.load(this, R.raw.startbath02, 1);// 2
        mSoundID[2] = mSound.load(this, R.raw.startbath03, 1);// 3
        mSoundID[3] = mSound.load(this, R.raw.startbath04, 1);// 4
        mSoundID[4] = mSound.load(this, R.raw.startbath05, 1);// 5
        mSoundID[5] = mSound.load(this, R.raw.startbath06, 1);// 6
        mSoundID[6] = mSound.load(this, R.raw.startbath07, 1);// 7
        mSoundID[7] = mSound.load(this, R.raw.startbath08, 1);// 8
        mSoundID[8] = mSound.load(this, R.raw.startbath09, 1);// 9
        mSoundID[9] = mSound.load(this, R.raw.startbath10, 1);// 10
        mSoundID[10] = mSound.load(this, R.raw.startbath11, 1);// 11
        mSoundID[11] = mSound.load(this, R.raw.startbath12, 1);// 12
        mSoundID[12] = mSound.load(this, R.raw.startbath13, 1);// 13
        mSoundID[13] = mSound.load(this, R.raw.startbath14, 1);// 14
        mSoundID[14] = mSound.load(this, R.raw.startbath15, 1);// 15
        mSoundID[15] = mSound.load(this, R.raw.endbath, 1);// 16
    }

    /**
     * 播放MP3资源
     *
     * @param resId 资源ID
     */
    @Override
    protected void StartMusic(int resId) {
        /*
         * 第一个参数为播放音频ID
         * 第二个 第三个为音量
         * 第四个为优先级
         * 第五个为是否循环播放
         * 第六个设置播放速度
         * 返回值 不为0即代表成功
         */
        mSound.play(resId, 1, 1, 0, 0, 1);
    }

    @Override
    public void timerTaskControlRun() {
        timeOutTemperature++;
        if (timeOutTemperature >= ManagerTimer.SENSOR_UP_TIME) {
            timeOutTemperature = 0;
            //addCommand(new SerialCommandEntity(SerialPortUtils.getReadTemperatureC, "getReadTemperatureC"));
        }
        timeOutControlNum++;
        if (timeOutControlNum * 1000 >= ManagerTimer.autoLockTime()) {
            onLock();
            timeOutControlNum = 0;
        }
    }

    @OnClick({R.id.item_txt_intercept, R.id.item_root_view})
    public void onViewClicked() {
        if (dialog != null && dialog.isShowing() && isCallBathPos) {
            CommonUtils.w("正在使用中，不需重复点击");
        } else {
            bathPosPresenter().getRoomStatus(true);
            isCallBathPos = true;
            getHandler().sendEmptyMessageDelayed(CALL_BATH_POS, 1000);
        }
    }

    @Override
    public void onUpdateSensor(boolean isSuccess) {
        //更新传感器信息
    }

    @Override
    public void onUpdateBathPos(int position, int state, boolean isUpdateSuccess) {
        if (isUpdateSuccess) {
            switch (state) {
                //结束洗浴并更新洗浴位信息成功
                case ReqConstant.BATH_POS_STATE_NO: {
                    //onLock();
                }
                break;
                //开始洗浴并更新洗浴位信息成功
                case ReqConstant.BATH_POS_STATE_BATHING: {

                }
                break;
                case ReqConstant.BATH_POS_STATE_RESERVE:
                    break;
                case ReqConstant.BATH_POS_STATE_FAULT:
                    break;
            }
        }
    }


    @Override
    public void onGetBathPosState(final List<HttpBathPosStateEntity> entities, boolean isChoosePos) {
        if (isChoosePos) {
            this.posStateEntities = entities;
            //弹出对话窗体（弹出全部洗浴位）
            dialog = new ChooseBathPosDialog(getThisContext(), MainBathShowActivity.this, entities);
            dialog.setListener(new ChooseBathPosDialog.OnChooseBathPosListener() {
                @Override
                public void onChoose(HttpBathPosStateEntity entity) {
                    switch (entity.getStatus()) {
                        case ReqConstant.BATH_POS_STATE_FAULT: {
                            localSendMessage(APP_TOAST, "浴位故障，请选择其他空闲浴位！");
                        }
                        break;
                        case ReqConstant.BATH_POS_STATE_NO: {
                            dialog.dismiss();
                            if (ManagerLocalData.isSupportLimitBath()) {
                                Date nowDate = getRealTime();
                                Date cutStartDate = getStartCutTime(nowDate);
                                Date cutEndDate = getEndCutTime(nowDate);
                                //时间超过12点不接受新订单
                                if (nowDate.getTime() > cutStartDate.getTime() && nowDate.getTime() < cutEndDate.getTime()) {
                                    messageDialog = new MessageDialog(getThisContext(), "亲，0-5点不能洗澡了");
                                    messageDialog.show();
                                } else {
                                    CommonUtils.w("有禁止洗浴");
                                    //暂时持有
                                    posStateEntity = entity;
                                    //弹出用户名密码登录界面
                                    loginMainDialog = new LoginMainDialog(getThisContext(), MainBathShowActivity.this, posStateEntity);
                                    loginMainDialog.setListener(MainBathShowActivity.this);
                                    loginMainDialog.show();
                                }
                            } else {
                                CommonUtils.w("无禁止洗浴");
                                //暂时持有
                                posStateEntity = entity;
                                //弹出用户名密码登录界面
                                loginMainDialog = new LoginMainDialog(getThisContext(), MainBathShowActivity.this, posStateEntity);
                                loginMainDialog.setListener(MainBathShowActivity.this);
                                loginMainDialog.show();
                            }
                        }
                        break;
                        case ReqConstant.BATH_POS_STATE_BATHING: {
                            dialog.dismiss();
                            //暂时持有
                            posStateEntity = entity;
                            //弹出快速登录界面
                            quickDialog = new LoginQuickDialog(getThisContext(), MainBathShowActivity.this, entity.getPhone(), posStateEntity);
                            quickDialog.setListener(MainBathShowActivity.this);
                            quickDialog.show();
                        }
                        break;
                        case ReqConstant.BATH_POS_STATE_RESERVE: {
                            dialog.dismiss();
                            if (ManagerLocalData.isSupportLimitBath()) {
                                Date nowDate = getRealTime();
                                Date cutStartDate = getStartCutTime(nowDate);
                                Date cutEndDate = getEndCutTime(nowDate);
                                //时间超过12点不接受新订单
                                if (nowDate.getTime() > cutStartDate.getTime() && nowDate.getTime() < cutEndDate.getTime()) {
                                    messageDialog = new MessageDialog(getThisContext(), "亲，0-5点不能洗澡了，取消预约即可");
                                    messageDialog.show();
                                } else {
                                    CommonUtils.w("有禁止-预约洗浴");
                                    //暂时持有
                                    posStateEntity = entity;
                                    //弹出快速登录界面
                                    quickDialog = new LoginQuickDialog(getThisContext(), MainBathShowActivity.this, entity.getPhone(), posStateEntity);
                                    quickDialog.setListener(MainBathShowActivity.this);
                                    quickDialog.show();
                                }
                            } else {
                                CommonUtils.w("无禁止-预约洗浴");
                                //暂时持有
                                posStateEntity = entity;
                                //弹出快速登录界面
                                quickDialog = new LoginQuickDialog(getThisContext(), MainBathShowActivity.this, entity.getPhone(), posStateEntity);
                                quickDialog.setListener(MainBathShowActivity.this);
                                quickDialog.show();
                            }
                        }
                        break;
                    }
                }
            });
            dialog.showWithAnim(R.style.dialogWindowAnimDelay);
        }
    }

    @Override
    public void onLoginUser(String phone, String password, HttpBathPosStateEntity posStateEntity) {
        HttpBathPosStateEntity httpBathPosStateEntity = null;
        //检查是否已存在，已存在切换到对应的洗浴位
        if (posStateEntities != null && posStateEntities.size() != 0) {
            for (int i = 0; i < posStateEntities.size(); i++) {
                HttpBathPosStateEntity entity = posStateEntities.get(i);
                if (entity.getPhone().equals(phone)) {
                    httpBathPosStateEntity = entity;
                    break;
                }
            }
        }
        if (httpBathPosStateEntity != null) {
            if (posStateEntity.getPos() == httpBathPosStateEntity.getPos()) {
                //请求登录
                loginPresenter().login(phone, password);
            } else {
                int pos = httpBathPosStateEntity.getPos() + 1;
                messageDialog = new MessageDialog(getThisContext(), "您正在使用" + pos + "号洗浴位，请切换到对应洗浴位!");
            }
        } else {
            //请求登录
            loginPresenter().login(phone, password);
        }
    }

    @Override
    public void onLogin(boolean isSuccess, HttpUserEntity entity) {
        if (isSuccess) {
            this.userEntity = entity;
            //localSendMessage(APP_TOAST, "登录成功");
            controlDialog = new BathControlDialog(getThisContext(), MainBathShowActivity.this, userEntity, posStateEntity);
            controlDialog.setListener(this);
            //显示Dialog
            controlDialog.show();
        }
    }

    @Override
    public void onLock() {
        this.userEntity = null;
        this.posStateEntity = null;
        this.posStateEntities = null;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //itemSettingRootView.setVisibility(View.GONE);
                itemShowSerialView.setVisibility(View.GONE);
                dismissDialog();
            }
        });
    }

    //请求订单开始服务
    @Override
    public void onStartBath() {
        orderPresenter().orderStart(userEntity, posStateEntity, true);
        NormalUtils.showRequestDialog(getThisContext());
    }

    //请求订单结束服务之前的获取用水量、关闭阀门、关闭储物柜
    @Override
    public void onEndBath() {
        currentDeviceEndPos = posStateEntity.getPos();
        sendOrderEnd(posStateEntity.getPos());
    }

    //打开储物柜门
    @Override
    public void onControlLocker() {
        if (ManagerLocalData.isSupportLocker() && posStateEntity != null) {
            int position = posStateEntity.getPos() + 1;
            //发送打开储物柜锁
            byte[] commandLocker = SerialPortUtils.getLockerC(position, true);
            addCommand(new SerialCommandEntity(commandLocker, SerialPortUtils.TYPE_COMMAND_LOCKER_OPEN));
        }
    }

    //订单开始
    @Override
    public void onOrderStart(HttpUserEntity userEntity, HttpBathPosStateEntity posStateEntity, boolean isSuccess, String message, boolean isDeviceSend) {
        if (isSuccess) {
            if (userEntity != null && posStateEntity != null) {
                if (controlDialog != null && controlDialog.isShowing()) {
                    controlDialog.updateStatus(posStateEntity.getPos(), ReqConstant.BATH_POS_STATE_BATHING, null);
                }
                localSendMessage(APP_TOAST, "洗浴开启成功");
                if (isDeviceSend) {
                    int resId = mSoundID[posStateEntity.getPos()];
                    localSendMessage(START_MUSIC, resId);
                }
                //bathPosPresenter().updateBathPosState(posStateEntity.getPos(), ReqConstant.BATH_POS_STATE_BATHING, 0, 0);
                if (ManagerLocalData.isUseSerialPort()) {
                    //发送开启供水开关
                    byte[] commandOpen = SerialPortUtils.getWaterValveC(posStateEntity.getPos() + 1, true);
                    //发送累计水量清零
                    byte[] commandClear = SerialPortUtils.getClearWaterUsageC(posStateEntity.getPos() + 1);
                    addCommand(new SerialCommandEntity(commandOpen, SerialPortUtils.TYPE_COMMAND_WATER_OPEN),
                            new SerialCommandEntity(commandClear, SerialPortUtils.TYPE_COMMAND_WATER_READ_USAGE));
                    CommonUtils.w("发送开启洗浴命令");
                }
                //洗浴开启，自动关闭洗浴位
                new MainBathAbsActivity.BaseHandler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog(controlDialog);
                    }
                }, 1000);
            }
        } else {
            if (controlDialog != null && controlDialog.isShowing()) {
                localSendMessage(APP_TOAST, message);
                controlDialog.updateStatus(posStateEntity.getPos(), ReqConstant.BATH_POS_START_FAIL, message);
            }
        }
    }

    //订单结束
    @Override
    public void onOrderEnd(HttpUserEntity userEntity, HttpBathPosStateEntity posStateEntity, boolean isSuccess, boolean isDeviceSend) {
        if (isSuccess) {
            //清除登录用户信息
            if (userEntity != null && posStateEntity != null) {
                localSendMessage(APP_TOAST, "洗浴结束成功");
                if (isDeviceSend) {
                    localSendMessage(START_MUSIC, mSoundID[15]);
                }
                //bathPosPresenter().updateBathPosState(posStateEntity.getPos(), ReqConstant.BATH_POS_STATE_NO, 0, 0);
                //洗浴结束，自动关闭洗浴位
                new MainBathAbsActivity.BaseHandler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog(controlDialog);
                    }
                }, 1000);
            }
        } else {
            localSendMessage(APP_TOAST, "洗浴结束失败");
        }
    }

    //接收推送分发处理
    @Override
    protected void pushAction(HttpGPushEntity pushEntity) {
        switch (pushEntity.getAction()) {
            case ReqConstant.USER_BEGIN: {
                HttpUserEntity pushUser = new HttpUserEntity(new HttpUserDetailEntity(pushEntity.getPhone()));
                HttpBathPosStateEntity pushPosStateEntity = new HttpBathPosStateEntity(pushEntity.getPosition());
                orderPresenter().orderStart(pushUser, pushPosStateEntity, false);
            }
            break;
            case ReqConstant.USER_END: {
                sendOrderEnd(pushEntity.getPosition());
            }
            break;
        }
    }

    @Override
    protected void submitTimeOut30() {
        HttpRoomEntity roomEntity = ManagerLocalData.getRoomData();
        if (roomEntity == null) return;
        Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call = AppMainService.getCommonService().getRoomStatus(roomEntity.getRoomId());
        call.enqueue(new Callback<ReqBaseEntity<List<HttpBathPosStateEntity>>>() {
            @Override
            public void onResponse(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Response<ReqBaseEntity<List<HttpBathPosStateEntity>>> response) {
                if (response.body() != null) {
                    List<HttpBathPosStateEntity> httpBathPosStateEntities = response.body().getData();
                    if (httpBathPosStateEntities == null) return;
                    for (int i = 0; i < httpBathPosStateEntities.size(); i++) {
                        final HttpBathPosStateEntity httpBathPosStateEntity = httpBathPosStateEntities.get(i);
                        if (httpBathPosStateEntity.getStatus() == ReqConstant.BATH_POS_STATE_BATHING) {
                            //洗浴的用户,开始时间
                            long x = getRealTime().getTime() - httpBathPosStateEntity.getTimeBegin();
                            if (x > 0) {
                                int y = (int) (x / (1000 * 60));
                                //TODO 默认最长洗浴时间（默认大于等于60分钟）
                                if (y >= 60) {
                                    //更新订单结束时间
                                    sendOrderEnd(httpBathPosStateEntity.getPos());
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Throwable t) {

            }
        });
    }

    @Override
    protected void submitAll(HttpRoomEntity roomEntity) {
        if (roomEntity == null) return;
        Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call = AppMainService.getCommonService().getRoomStatus(roomEntity.getRoomId());
        call.enqueue(new Callback<ReqBaseEntity<List<HttpBathPosStateEntity>>>() {
            @Override
            public void onResponse(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Response<ReqBaseEntity<List<HttpBathPosStateEntity>>> response) {
                if (response.body() != null) {
                    List<HttpBathPosStateEntity> httpBathPosStateEntities = response.body().getData();
                    if (httpBathPosStateEntities == null) return;
                    for (int i = 0; i < httpBathPosStateEntities.size(); i++) {
                        HttpBathPosStateEntity httpBathPosStateEntity = httpBathPosStateEntities.get(i);
                        if (httpBathPosStateEntity.getStatus() == ReqConstant.BATH_POS_STATE_BATHING) {
                            sendOrderEnd(httpBathPosStateEntity.getPos());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Throwable t) {

            }
        });
    }

    //获取到选中位置的累计用水量
    @Override
    protected void showBathPosWaterUsage(final int pos, final DeviceWaterUsageEntity entity) {
        final HttpRoomEntity roomEntity = ManagerLocalData.getRoomData();
        //localSendMessage(APP_TOAST, "房间信息:" + new Gson().toJson(roomEntity));
        if (roomEntity == null) return;
        Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call = AppMainService.getCommonService().getRoomStatus(roomEntity.getRoomId());
        call.enqueue(new Callback<ReqBaseEntity<List<HttpBathPosStateEntity>>>() {
            @Override
            public void onResponse(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Response<ReqBaseEntity<List<HttpBathPosStateEntity>>> response) {
                //localSendMessage(APP_TOAST, "洗浴位信息:" + new Gson().toJson(response.body()));
                if (response.body() == null) return;
                if (response.body().getCode() != ReqConstant.NET_RESULT_OK) return;
                List<HttpBathPosStateEntity> httpBathPosStateEntities = response.body().getData();
                if (httpBathPosStateEntities == null) return;
                HttpBathPosStateEntity httpBathPosStateEntity = null;
                for (int i = 0; i < httpBathPosStateEntities.size(); i++) {
                    if (httpBathPosStateEntities.get(i).getPos() == pos - 1) {
                        httpBathPosStateEntity = httpBathPosStateEntities.get(i);
                        break;
                    }
                }
                if (httpBathPosStateEntity == null) return;
                HttpUserEntity posUser = new HttpUserEntity(new HttpUserDetailEntity(httpBathPosStateEntity.getPhone()));
                HttpBathPosStateEntity posPosStateEntity = new HttpBathPosStateEntity(httpBathPosStateEntity.getPos());
                //计费并请求订单结束服务
                Date endDate = getRealTime();
                Long time = endDate.getTime() - httpBathPosStateEntity.getTimeBegin();
                float minute = time / (1000 * 60);
                String xxx = "时间：" + minute +
                        "\n开始时间：" + getDateTime(new Date(httpBathPosStateEntity.getTimeBegin())) +
                        "\n结束时间：" + getDateTime(endDate) +
                        "\n水量：" + entity.getWaterUsage();
                localSendMessage(APP_TOAST, "洗浴信息：" + xxx);
                if (time < 0) return;
                float xiyuda = (float) roomEntity.getFee_xi_yu_da() * minute;
                float xiyuxiao = (float) roomEntity.getFee_xi_yu_xiao() * entity.getWaterUsage();
                boolean isDevicceSend = currentDeviceEndPos == httpBathPosStateEntity.getPos();
                currentDeviceEndPos = -1;
                orderPresenter().orderEnd(isDevicceSend, posUser, posPosStateEntity, entity.getWaterUsage(), minute, xiyuda + xiyuxiao, xiyuda, xiyuxiao, 0, 0);
            }

            @Override
            public void onFailure(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Throwable t) {

            }
        });
    }

    private String getDateTime(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA);
        return dateFormat.format(date);
    }

    //获取到当前房间的水温
    @Override
    protected void showBathPosTemperature(DeviceTemperatureEntity entity) {
        String deviceSensor = ReqConstant.DEVICE_SENSOR_TEMPERATURE;
        List<HttpSensorEntity> sensorEntities = new ArrayList<>();
        HttpSensorEntity sensorEntity = new HttpSensorEntity(deviceSensor, entity.getTemperature());
        sensorEntities.add(sensorEntity);
        //请求传感器值上传服务
        bathPosPresenter().updateSensor(sensorEntities);
    }

    //控制屏被操作时计时清零
    @Override
    public void onOperate() {
        timeOutControlNum = 0;
    }


}